<script setup lang="ts">
import { ref, onMounted, reactive, watch, toRaw } from "vue";
import { ElMessage, ElForm, ElFormItem, ElSwitch, ElInputNumber, ElButton, ElMessageBox } from "element-plus";
import { useRoute } from "vue-router";
import { useI18n } from 'vue-i18n';
import { getProductDeptGroupConfigsApi, setProductDeptGroupConfigsApi } from '@/api/configs/productDeptConfig';
import { formatTimestampToDatetime } from "@/utils/appCommon/timeUtil";

const { t } = useI18n();

const configGroupName = "receivePolicy";

const props = defineProps<{
  searchForm: {
    default: {
      deptId: 0,
      productId: 0,
    };
  };
}>();

// 定义配置项类型
interface ReceivePolicyConfig {
  isReceiveParam: boolean;       // 是否接收参数数据
  isReceiveWave: boolean;        // 是否接收波形
  isRestrict: boolean;    // 是否限制接收频率
  frequency: number;          // 接收频率（秒）
}

const route = useRoute();
const formRef = ref<InstanceType<typeof ElForm>>();

const defaultConfig = {
  isReceiveParam: false,
  isReceiveWave: false,
  isRestrict: false,
  frequency: 10,
}

// 初始化表单数据
const formData = reactive<{
  productId: number;
  deptId: number;
  groupName: string;
  config: ReceivePolicyConfig;
  updatedAt: string;
}>({
  productId: 0,
  deptId: 0,
  groupName: configGroupName,
  config: Object.assign({}, defaultConfig),
  updatedAt: ''
});

// 表单验证规则
const rules = reactive({
  'config.isReceiveParam': [{
    type: 'boolean',
    required: true,
    message: t('configs.deptProductConfigPage.common.validationFailed'),
    trigger: 'change'
  }],
  'config.isReceiveWave': [{
    type: 'boolean',
    required: true,
    message: t('configs.deptProductConfigPage.common.validationFailed'),
    trigger: 'change'
  }],
  'config.frequency': [
    {
      required: false,
      message: '请输入接收频率',
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (formData.config.isRestrict && (!value || value <= 0)) {
          callback(new Error(t('configs.deptProductConfigPage.dataReceivePolicy.frequency') + ' ' + 'must be greater than 0'));
        } else {
          callback();
        }
      }
    }
  ],
});
onMounted(() => {
  if (props.searchForm) {
    formData.productId = props.searchForm.productId;
    formData.deptId = props.searchForm.deptId;
    loadConfigData();
  }
});
watch(() => props.searchForm, (newVal:any) => {
  if (newVal) {
    console.log(newVal);
    formData.productId = newVal.productId;
    formData.deptId = newVal.deptId;
    loadConfigData();
  }
},{
  deep: true
});

const loadConfigData = () => {
  console.log(toRaw(formData))
  if (formData.productId && formData.deptId) {
    getProductDeptGroupConfigsApi({
      productId: formData.productId,
      deptId: formData.deptId,
      groupName: formData.groupName
    }).then(res => {
      if (res.code === 0 && res.data?.configs) {
        formData.updatedAt = res.data.updatedAt || '';
        try {
          const configData = JSON.parse(res.data.configs[0]?.configValue || '{}');
          Object.assign(formData.config, configData);
        } catch (e) {
          console.error('解析配置数据失败', e);
        }
      }
    });
  }
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  try {
    // 表单验证
    await formRef.value.validate();

    // 准备提交数据
    const submitData = {
      productId: formData.productId,
      deptId: formData.deptId,
      groupName: formData.groupName,
      configs: [{
        configKey: 'receivePolicy',
        configValue: JSON.stringify(formData.config),
        configDesc: ''
      }]
    };

    // 二次确认
    ElMessageBox.confirm(
      t('configs.deptProductConfigPage.dataReceivePolicy.confirmSubmit'),
      'Confirm Submit',
      {
        confirmButtonText: t('configs.deptProductConfigPage.common.confirmButtonText'),
        cancelButtonText: t('configs.deptProductConfigPage.common.cancelButtonText'),
        type: 'warning',
      }
    ).then(async () => {
      await setProductDeptGroupConfigsApi(submitData);
      ElMessage.success(t('configs.deptProductConfigPage.common.saveSuccess'));
    }).catch(() => {
      ElMessage.info(t('configs.deptProductConfigPage.common.saveCancelled'));
    });
  } catch (error) {
    ElMessage.error(t('configs.deptProductConfigPage.common.validationFailed'));
  }
};

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields();
};

</script>

<template>
  <el-form ref="formRef" :model="formData" :rules="rules" label-width="180px" class="form-container">
<!--    <el-form-item label="产品" prop="productId">-->
<!--      <el-input :value="formData.productId " disabled />-->
<!--    </el-form-item>-->
<!--    <el-form-item label="部门" prop="deptId">-->
<!--      <el-input :value="formData.deptId" disabled />-->
<!--    </el-form-item>-->
    <el-form-item :label="t('configs.deptProductConfigPage.dataReceivePolicy.configGroupName')" prop="groupName">
      <el-input v-model="formData.groupName" disabled />
    </el-form-item>

    <!-- 数据接收策略配置项 -->
    <el-form-item :label="t('configs.deptProductConfigPage.dataReceivePolicy.isReceiveParam')" prop="config.isReceiveParam">
      <el-switch v-model="formData.config.isReceiveParam" />
    </el-form-item>

    <el-form-item :label="t('configs.deptProductConfigPage.dataReceivePolicy.isReceiveWave')" prop="config.isReceiveWave">
      <el-switch v-model="formData.config.isReceiveWave" />
    </el-form-item>

    <el-form-item :label="t('configs.deptProductConfigPage.dataReceivePolicy.isRestrict')" prop="config.isRestrict">
      <el-switch v-model="formData.config.isRestrict" />
    </el-form-item>

    <el-form-item
      :label="t('configs.deptProductConfigPage.dataReceivePolicy.frequency')"
      prop="config.frequency"
      v-if="formData.config.frequency"
    >
      <el-input-number
        v-model="formData.config.frequency"
        :min="1"
        :step="1"
        controls-position="right"
        :placeholder="t('configs.deptProductConfigPage.dataReceivePolicy.frequency')"
      />
      <div class="form-hint">{{ t('configs.deptProductConfigPage.dataReceivePolicy.frequencyHint') }}</div>
    </el-form-item>

    <!-- 更新时间显示 -->
    <el-form-item :label="t('configs.deptProductConfigPage.dataReceivePolicy.updatedAt')">
      <el-input :value="formatTimestampToDatetime(formData.updatedAt)" disabled :placeholder="t('configs.deptProductConfigPage.common.noUpdateTime')" />
    </el-form-item>

    <el-form-item class="form-actions">
      <el-button type="primary" @click="submitForm">{{ t('configs.deptProductConfigPage.dataReceivePolicy.submit') }}</el-button>
      <el-button @click="resetForm">{{ t('configs.deptProductConfigPage.dataReceivePolicy.reset') }}</el-button>
    </el-form-item>
  </el-form>
</template>

<style scoped lang="scss">
.form-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
}
.form-actions {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-top: 30px;
}
.form-hint {
  color: #606266;
  font-size: 12px;
  margin-top: 5px;
}
::v-deep .el-form-item__content {
  flex: 1;
}
</style>
